package cc.cocosky.imclient;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class ByteUtil {

	public static byte[] int2Bytes(int x) {
		byte[] buff = new byte[4];
		putInt(buff, x, 0);
		return buff;
	}

	public static int bytes2Int(byte[] buff) {
		return getInt(buff, 0);
	}

	public static int getInt(byte[] buff, int srcPos) {
		int mask = 0xff;
		int temp = 0;
		int n = 0;
		for (int i = 0; i < 4; i++) {
			n <<= 8;
			temp = buff[srcPos + i] & mask;
			n |= temp;
		}
		return n;
	}

	public static void putInt(byte[] buff, int x, int desPos) {
		buff[desPos] = (byte) (x >> 24);
		buff[desPos + 1] = (byte) (x >> 16);
		buff[desPos + 2] = (byte) (x >> 8);
		buff[desPos + 3] = (byte) (x);
	}
	
	public static int readLength(InputStream in) throws IOException {
		byte[] lenBytes = readData(in, 4);
		return bytes2Int(lenBytes);
	}

	public static byte[] readData(InputStream in, int length) throws IOException {
		byte[] data = new byte[length];
		int reads = 0; // 已读的总长度
		int len; // 本次将读到的长度
		while (true) {
			len = in.read(data, reads, length - reads);
			if (len < 0) {
				throw new IOException("没流可读了！");
			}
			reads += len;
			if (reads == length) {
				break;
			}
		}
		return data;
	}

	public static void writeLength(OutputStream out, int length) throws IOException {
		byte[] lenBytes = int2Bytes(length);
		writeData(out, lenBytes);
	}
	
	public static void writeData(OutputStream out, byte[] data) throws IOException {
		out.write(data);
	}

	public static ByteBuffer readData(SocketChannel channel, int length) throws IOException {
		ByteBuffer data = ByteBuffer.allocate(length);
		int reads = 0; // 已读的总长度
		long len; // 本次将读到的长度
		while (true) {
			len = channel.read(data);
			if (len <= 0) {
				throw new IOException("没流可读了！");
			}
			reads += len;
			if (reads == length) {
				break;
			}
		}
		return data;
	}

	public static int readLength(SocketChannel channel) throws IOException {
		ByteBuffer data = readData(channel, 4);
		data.flip();
		return data.getInt();
	}

}
